package com.sxbang.friday.controller;

import com.sxbang.friday.base.result.PageTableRequest;
import com.sxbang.friday.base.result.Results;
import com.sxbang.friday.dto.UserDto;
import com.sxbang.friday.model.SysUser;
import com.sxbang.friday.service.UserService;
import com.sxbang.friday.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 通过用户名获取用户
	 * @param username
	 * @return
	 */
	@GetMapping("/{username}")
    @ResponseBody
	public SysUser user(@PathVariable String username) {
	    log.info("UserController.user(): param ( username = " + username +" )");
		return userService.getUser(username);
	}

	/**
	 * 分页获取所有用户
	 * @return Results<SysUser>
	 */
	@ResponseBody
    @GetMapping("/list")
	public Results<SysUser> getUsers(PageTableRequest pageTableRequest) {
		//获取前端传递过来的limit和page并计算出offset
		pageTableRequest.countOffset();
		return userService.getAllUsersByPage(pageTableRequest.getOffset(),pageTableRequest.getLimit());
	}

	/**
	 *跳转新增用户
	 * @return String
	 */
	@GetMapping("/add")
	public String addUser(Model model) {
		model.addAttribute(new SysUser());
		return "user/user-add";
	}

	/**
	 *新增用户
	 * @return String
	 */
	@PostMapping("/add")
    @ResponseBody
	public Results<SysUser> addUser(UserDto userDto,Integer roleId) {
		//设置用户状态
		userDto.setStatus(1);
		//加密密码
		userDto.setPassword(MD5.crypt(userDto.getPassword()));
		Results results = userService.save(userDto, roleId);
		return  results;
	}

	//适配前端的日期和后台的格式
	String pattern = "yyyy-MM-dd";
	@InitBinder
	public void initBinder(WebDataBinder binder, WebRequest request){
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(pattern),true));
	}

}
